import Phaser from 'phaser'
import { TEAM_META, type TeamKey, type RewardKey, createInitialScores, type GroupScores } from '../utils/GroupCompetition.js';
import { ResponsiveUtils } from '../utils/ResponsiveUtils.js';

declare global {
   }
}

export class GroupBar extends Phaser.GameObjects.Container {
  scores: GroupScores
  bars, Phaser.GameObjects.Container> = {}
  icons, string> = { flower: '🌸', star: '⭐', earth: '🌍' }
  activeIndex= 0
  selectors, Phaser.GameObjects.Rectangle> = {}
  allowed: RewardKey
  responsive: ResponsiveUtils

  constructor(scene: Phaser.Scene, x, y, width, allowed) {
    super(scene, x, y)
    this.allowed = allowed
    this.scores = createInitialScores()
    this.responsive = ResponsiveUtils.getInstance()
    this.setSize(width, 100)
    this.buildUI(width)
  }

  buildUI(width) {
    const keys= ['red','orange','yellow','green','cyan','blue','purple']
    const barWidth = Math.floor((width - 60) / keys.length)

    keys.forEach((k, idx) => {
      const group = this.scene.add.container(idx * (barWidth + 10), 0)
      const meta = TEAM_META[k]

      // 主背景区域（用于队伍选择）
      const bg = this.scene.add.rectangle(0, 0, barWidth - 40, 80, meta.color, 0.35).setOrigin(0)
      const outline = this.scene.add.rectangle(0, 0, barWidth - 40, 80).setOrigin(0).setStrokeStyle(2, 0xFDE047, 0)
      const name = this.scene.add.text(10, 8, meta.name, { fontSize: '16px', color: '#E5E7EB' })
      const counts = this.scene.add.text(10, 35, this.formatCounts(k), { fontSize: '20px', color: '#FFFFFF' })

      // 给分数文本设置一个唯一标识，便于后续更新
      counts.setData('teamKey', k)
      counts.setData('isScoreText', true)

      // 按钮区域背景
      const btnAreaBg = this.scene.add.rectangle(barWidth - 40, 0, 40, 80, 0x1F2937, 0.8).setOrigin(0)

      // 添加加分按钮（向上箭头） - 使用绝对位置
      const addBtn = this.scene.add.rectangle(barWidth - 20, 20, 30, 25, 0x059669, 0.8).setOrigin(0.5)
      const addIcon = this.scene.add.text(barWidth - 20, 20, '▲', {
        fontSize: '14px', color: '#FFFFFF'
      }).setOrigin(0.5)

      // 添加减分按钮（向下箭头）
      const subBtn = this.scene.add.rectangle(barWidth - 20, 55, 30, 25, 0xDC2626, 0.8).setOrigin(0.5)
      const subIcon = this.scene.add.text(barWidth - 20, 55, '▼', {
        fontSize: '14px', color: '#FFFFFF'
      }).setOrigin(0.5)

      // 设置按钮交互
      addBtn.setInteractive({ useHandCursor: true })
      subBtn.setInteractive({ useHandCursor: true })

      addBtn.on('pointerdown', () => {
        console.log(`Adding point to team ${k}`)
        this.addReward(k, this.allowed)
      })

      subBtn.on('pointerdown', () => {
        console.log(`Subtracting point from team ${k}`)
        this.subtractReward(k, this.allowed)
      })

      // 按钮悬停效果
      addBtn.on('pointerover', () => addBtn.setFillStyle(0x10B981))
      addBtn.on('pointerout', () => addBtn.setFillStyle(0x059669))
      subBtn.on('pointerover', () => subBtn.setFillStyle(0xEF4444))
      subBtn.on('pointerout', () => subBtn.setFillStyle(0xDC2626))

      // 队伍选择区域（只在左侧主区域）
      const teamSelectArea = this.scene.add.rectangle(0, 0, barWidth - 40, 80, 0x000000, 0).setOrigin(0)
      teamSelectArea.setInteractive({ useHandCursor: true })
      teamSelectArea.on('pointerdown', () => {
        console.log(`Team ${k} (index ${idx}) selected`)
        this.setActiveIndex(idx)
      })

      // 队伍悬停效果
      teamSelectArea.on('pointerover', () => {
        bg.setAlpha(0.6)
      })
      teamSelectArea.on('pointerout', () => {
        bg.setAlpha(0.35)
      })

      group.add([bg, outline, name, counts, btnAreaBg, addBtn, addIcon, subBtn, subIcon, teamSelectArea])
      group.setDepth(1000)

      this.add(group)
      this.bars[k] = group
      this.selectors[k] = outline
    })

    // 默认选中第一个
    this.setActiveIndex(0)

    // 操作提示（教师用）
    const keyMap,string> = { flower: 'F加🌸', star: 'S加⭐', earth: 'E加🌍' }
    const help = this.scene.add.text(0, 88, `快捷键：1-7选择队伍；${keyMap[this.allowed]}  R重置；Ctrl/Cmd+S 保存`, { fontSize: '14px', color: '#9CA3AF' })
    this.add(help)
  }

  formatCounts(team): string {
    const r = this.scores.rewards[team]
    const icon = this.icons[this.allowed]
    const count = r[this.allowed]
    return `${icon} ${count}分` // 添加空格和"分"字，更清晰
  }

  refreshUI() {
    (Object.keys(this.bars) as TeamKey[]).forEach((k) => {
      const container = this.bars[k]
      // 使用数据标识来准确找到分数文本
      const countsText = container.getAll().find(o => (o as any).getData && (o as any).getData('isScoreText') && (o as any).getData('teamKey') === k) as Phaser.GameObjects.Text
      if (countsText) {
        const newText = this.formatCounts(k)
        console.log(`Updating ${k} score to: ${newText}`)
        countsText.setText(newText)
      } else {
        console.log(`Could not find score text for team ${k}`)
      }
    })
  }

  addReward(team, type) {
    if (type !== this.allowed) return
    this.scores.rewards[team][type]++
    this.refreshUI()
    this.showAddRewardEffect(team, type)
  }

  subtractReward(team, type) {
    if (type !== this.allowed) return
    if (this.scores.rewards[team][type] > 0) {
      this.scores.rewards[team][type]--
      this.refreshUI()
      this.showSubtractRewardEffect(team, type)
    }
  }

  showAddRewardEffect(team, type) {
    const teamContainer = this.bars[team]
    if (!teamContainer) return

    // 创建飞入的奖励图标
    const icon = this.icons[type]
    const effectText = this.scene.add.text(teamContainer.x + 50, teamContainer.y - 30, `+${icon}`, {
      fontSize: '24px',
      color: '#FDE047'
    })

    this.add(effectText)

    // 动画效果：从上方飞入，然后消失
    this.scene.tweens.add({
      targets,
      y: teamContainer.y + 10,
      alpha: 0,
      scale: 1.5,
      duration: 800,
      ease: 'Power2',
      onComplete: () => {
        effectText.destroy()
      }
    })

    // 让整个队伍条闪烁一下
    const teamBg = teamContainer.getAll().find(obj => obj instanceof Phaser.GameObjects.Rectangle) as Phaser.GameObjects.Rectangle
    if (teamBg) {
      const originalAlpha = teamBg.alpha
      this.scene.tweens.add({
        targets,
        alpha: 0.8,
        duration: 200,
        yoyo,
        repeat: 1,
        onComplete: () => {
          teamBg.alpha = originalAlpha
        }
      })
    }
  }

  showSubtractRewardEffect(team, type) {
    const teamContainer = this.bars[team]
    if (!teamContainer) return

    // 创建减分效果
    const icon = this.icons[type]
    const effectText = this.scene.add.text(teamContainer.x + 50, teamContainer.y - 30, `-${icon}`, {
      fontSize: '24px',
      color: '#EF4444'
    })

    this.add(effectText)

    // 动画效果：向下飞出并消失
    this.scene.tweens.add({
      targets,
      y: teamContainer.y + 50,
      alpha: 0,
      scale: 1.5,
      duration: 800,
      ease: 'Power2',
      onComplete: () => {
        effectText.destroy()
      }
    })

    // 让整个队伍条闪烁红色
    const teamBg = teamContainer.getAll().find(obj => obj instanceof Phaser.GameObjects.Rectangle) as Phaser.GameObjects.Rectangle
    if (teamBg) {
      const originalAlpha = teamBg.alpha
      this.scene.tweens.add({
        targets,
        alpha: 0.8,
        tint: 0xFF6B6B,
        duration: 200,
        yoyo,
        repeat: 1,
        onComplete: () => {
          teamBg.alpha = originalAlpha
          teamBg.clearTint()
        }
      })
    }
  }

  resetAll() {
    this.scores = createInitialScores()
    this.refreshUI()
  }

  async save() {
    try {
      if (window.STAR_API?.saveGroupScores) {
        const res = await window.STAR_API.saveGroupScores({ ts: Date.now(), scores: this.scores, allowed: this.allowed })
        return res
      }
    } catch (e) {
      console.warn('Save failed', e)
    }
    return { ok: false }
  }

  setActiveIndex(idx) {
    this.activeIndex = idx
    const keys= ['red','orange','yellow','green','cyan','blue','purple']
    keys.forEach((k, i) => {
      const sel = this.selectors[k]
      sel.setStrokeStyle(2, 0xFDE047, i===idx ? 1 : 0)
    })
  }

  getActiveTeam(): TeamKey {
    const keys= ['red','orange','yellow','green','cyan','blue','purple']
    return keys[this.activeIndex]
  }
}

